<script lang="ts">
import { defineComponent } from "vue";
import { delayTask } from "@/utils/timer";

import MediaVideo from "@/components/media/video.vue";

export default defineComponent({
  components: { MediaVideo },
  props: {
    modelValue: { type: Number, default: 0 },
    listData: { type: Array, required: true },
    labelKey: { type: String, default: "url" },
    autoplay: Boolean,
    mode: { type: String, default: "aspectFill" },
    objectFit: { type: String, default: "cover" },
  },
  emits: {
    "update:modelValue": (value: number) => typeof value === "number",
  },
  setup(props, ctx) {
    let timer = 0;

    const swipeChange = (e: MiniApp.Event<{ current: number }>) => {
      clearTimeout(timer);
      timer = delayTask(500, () => {
        ctx.emit("update:modelValue", e.detail.current);
      });
    };
    return { swipeChange };
  },
});
</script>

<template>
  <view class="swipe">
    <swiper
      class="swipe-swiper"
      :current="modelValue"
      circular
      :autoplay="autoplay"
      @change="swipeChange"
    >
      <swiper-item v-for="(i, d) of listData" :key="d">
        <MediaVideo
          v-if="i.type === 'video'"
          :src="i.url"
          :poster="i.poster"
          muted
          :showProgress="false"
          autoplay
          :objectFit="objectFit"
        />
        <image class="swipe-img" v-else :src="i[labelKey]" :mode="mode" />
      </swiper-item>
    </swiper>
  </view>
</template>

<style lang="scss">
.swipe {
  height: 100%;

  .swipe-swiper {
    height: 100%;
  }

  .swipe-img {
    display: block;
    width: 100%;
    height: 100%;
  }
}
</style>